import store from '@/store';
import ElementUI from 'element-ui';
import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
import DefaultView from "../layout/default.vue";

Vue.use(VueRouter)

const routes: Array<RouteConfig> = [
  {
    path: '/admin',
    name: 'Layout',
    component: DefaultView,
    children: [
      {
        path: "home",
        name:"Home",
        meta:{
          auth: true
        },
        component: ()=>import("../views/admin/HomeView.vue")
      },
      {
        path:"classes_edit",
        name: "ClassesEdit",
        meta:{
          auth: true
        },
        component: ()=>import("../views/admin/ClassesEditView.vue")
      },
      {
        path:"student_edit",
        name: "StudentEdit",
        meta:{
          auth: true
        },
        component: ()=>import("../views/admin/StudentEditView.vue")
      },
      {
        path: "department_edit",
        name:"DepartmentEdit",
        meta:{
          auth: true
        },
        component: ()=>import("../views/admin/DepartmentEditView.vue")
      },
      {
        path: "/",
        name:"Home",
        redirect:"home"
      },
    ]
  },
  {
    path: "/login",
    name: "Login",
    meta:{
      auth: false
    },
    component: ()=>import("../views/LoginView.vue")
  },
  {
    path:"/",
    redirect:"/admin/home"
  },
  {
    path:"*",
    name:"404",
    meta:{
      auth: false
    },
    component: ()=>import("../views/NotFound.vue")
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


router.beforeEach((to,from,next)=>{
  // 如果meta未曾指定需要登录则直接放行
  if(!to.meta || !to.meta.auth) return next();
  if(!store.state.token){
    ElementUI.Message.error("您还未登录，请先登录");
    next("/login");
  }
  next();
})

export default router
